<?php
/**
 * I know no such things as genius,it is nothing but labor and diligence.
 *
 * @copyright (c) 2015~2019 xinran All rights reserved.
 * @author 晋<657306123@qq.com>
 */

namespace app\common\middleware;

use app\Request;
use app\View;
use think\Config;
use Xin\Thinkphp5\Support\OS;

/**
 * 初始化模块
 */
class ViewInit{

	/**
	 * @var \app\Request
	 */
	private $request;

	/**
	 * @var \think\Config
	 */
	private $config;

	/**
	 * @var \app\View
	 */
	private $view;

	/**
	 * ViewInit constructor.
	 *
	 * @param \app\Request  $request
	 * @param \think\Config $config
	 * @param \app\View     $view
	 */
	public function __construct(Request $request, Config $config, View $view){
		$this->request = $request;
		$this->config = $config;
		$this->view = $view;
	}

	/**
	 * @param \app\Request $request
	 * @param \Closure     $next
	 * @return mixed
	 */
	public function handle(Request $request, \Closure $next){
		// 初始化模板变量
		$this->initTemplateVars();

		// 初始化主题路径
		$this->initThemePath();

		// 初始化资源版本号
		$this->initResourceVersion();

		return $next($request);
	}

	/**
	 * 初始化模板变量
	 */
	private function initTemplateVars(){
		$tplReplaceString = array_merge([
			'__UPLOAD__'  => OS::getWebUploadsPath(),
			'__STATIC__'  => OS::getWebStaticPath(),
			'__PLUGINS__' => OS::getWebVendorPath(),
			'__IMG__'     => OS::getWebImagesPath(),
			'__JS__'      => OS::getWebJsPath(),
			'__CSS__'     => OS::getWebCssPath(),
			'__FONT__'    => OS::getWebFontsPath(),
			//			'__PLUGINS_PATH__' => SafePath::getPluginsPath(),
		], (array)$this->config->get('template.tpl_replace_string'));

		// 写入配置
		$this->config->set('template.tpl_replace_string', $tplReplaceString);

		//配置模板变量
		$this->view->config('tpl_replace_string', $tplReplaceString);
	}

	/**
	 * 初始化主题路径
	 */
	private function initThemePath(){
		//		$theme = Config::get('theme');
		//		if(!empty($theme)){
		//			$theme = Env::get('module_path')."view".DIRECTORY_SEPARATOR."{$theme}".DIRECTORY_SEPARATOR;
		//			Config::set('template.view_path', $theme);
		//			View::config('view_path', $theme);
		//		}
	}

	/**
	 * 初始化资源版本号
	 */
	private function initResourceVersion(){
		$resVersion = $this->config->get('web.res_version');
		if(empty($resVersion)){
			$resVersion = 'v1.0.0';
		}

		$this->view->assign('__res_ver__', OS::isLocal() ? $this->request->time() : $resVersion);
	}
}
